package org.epidroid.epidroid.chronos.ui;

import org.epidroid.epidroid.R;
import org.epidroid.epidroid.chronos.engine.Chronos;
import org.epidroid.epidroid.chronos.engine.objects.ChronosNode;
import org.epidroid.epidroid.chronos.service.ChronosService;
import org.epidroid.epidroid.chronos.service.ChronosServiceBinder;
import org.epidroid.epidroid.chronos.service.IChronosService;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.ListView;

public class ChronosFavActivity extends Activity {

	private IChronosService _service = null;
	private ListView _list = null;
	private ChronosFavAdapter _adapter = null;
	private ServiceConnection _serviceConnection = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		bindWithChronosService();
	}
	
	@Override
	protected void onDestroy() {
		//unbindService(_serviceConnection);
		super.onDestroy();
	}

	@Override
	protected void onResume() {
		if (null != _adapter)
			_adapter.notifyDataSetChanged();
		super.onResume();
	}

	private void bindWithChronosService() {
		Intent intent = new Intent(this, ChronosService.class);

		_serviceConnection = new ServiceConnection() {
			public void onServiceConnected(ComponentName name,
					IBinder servicebinder) {
				IChronosService service = ((ChronosServiceBinder) servicebinder)
						.getService();
				_service = service;
				init();
			}

			public void onServiceDisconnected(ComponentName name) {
				Log.i(Chronos.LOGCAT, "Service has disconnected!");
			}
		};

		if (!getApplicationContext().bindService(intent, _serviceConnection,
				Context.BIND_AUTO_CREATE)) {
			Log.i(Chronos.LOGCAT, "Could not bind with service");
		}
	}

	public void init() {
		setContentView(R.layout.chronos_favs);

		_list = (ListView) findViewById(R.id.chronos_favs_list);
		_adapter = new ChronosFavAdapter(this, R.layout.chronos_group_item,
				_service.getFavorites(), _service);
		_list.setAdapter(_adapter);
		_list.setDivider(null); // TODO: do that in xml layout
		_adapter.notifyDataSetChanged();
	}

	public void openGroup(ChronosNode node, int type) {
		Intent intent = new Intent(this, ChronosViewActivity.class);
		intent.putExtra("group", node.getName());
		intent.putExtra("type", type);
		startActivity(intent);
	}
}
